sách gpt4 ai đã đi

javascript - Mô tả [Danh sách ngẫu nhiên]

In lại 作者:行者123 更新时间:2023-12-03 02:52:22 26 4
mua khóa gpt4 Nike

JavaScript 正在随机化列表..我不明白它是如何工作的,请帮我详细解释一下 JavaScript 是如何工作的。


  • Sunday

  • Monday

  • Tuesday

  • Wednesday

  • Thursday

  • Friday

  • Saturday





var ul = document.getElementById("name"),
temp = ul.cloneNode(true),
i = temp.children.length + 1;

while( i-- > 0 )
temp.appendChild( temp.children[Math.random() * i |0] );

ul.parentNode.replaceChild(temp, ul);


1 Câu trả lời

//saving 
    element wiсh id is 'name' to the ul variable
    var ul = document.getElementById("name"),
    //cloning this ul and all its child elements to the temp variable;
    //cloneNode(true) means deep copy, cloneNode(false) copies only the node
    temp = ul.cloneNode(true),
    // we will start from the end of the child nodes array and go down
    i = temp.children.length + 1;

    //at each iteration we will decrement i and compare it to 0
    while (i-- > 0)
    //while this condition is true we take a random node from the child elements array;
    //here we use Math.random() to generate a random number from 0 to 1,
    //multiply it by i to get a number from 0 to i and then use bitwise OR with 0
    //to convert this floating point number to an integer (see below for more details);
    //and then we append this random child to the temp; if a node already exists
    //in the DOM, then appendNode will remove it before appending, so we just replace
    //the nodes in random order
    temp.appendChild(temp.children[Math.random() * i | 0]);

    //and finally we replace the old ul with a new one
    ul.parentNode.replaceChild(temp, ul);

有关按位或的更多信息,请查看 đây

关于javascript - 说明【随机列表】,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47789847/

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com