javascript - The shift() method of js is invalid?
滿天的星座
滿天的星座 2017-07-05 10:45:34
0
4
1045

As the title says, the code is as follows:

<ul class="demo">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
<script>
    var l = document.getElementsByClassName("demo")[0];
    var a = l.children;
    var r=a.shift();
    console.log(r);//报错:a.shift is not a function?
</script>

Array-like objects cannot call the shift method api?

滿天的星座
滿天的星座

reply all(4)
扔个三星炸死你

The class array is not an array, and there is no related API that inherits the array.
You can use call or apply to bind this,
For example

var r = [].shift.call(a)

ps: shift also involves operating the contents of the array. I just tried it and forced call to shift the array object. It will report that the length of the related object cannot be modified. If it also involves DOM processing, it is recommended to use related DOM operations. For example, removeChild will not be expanded. Relevant information about DOM array objects can be found in mdn, such as: https://developer.mozilla.org...

代言

Shift will modify the original array, causing the length property to change, but length is read-only. It can be used in the following ways.

<ul class="demo">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
</body>

<script>
    var l = document.getElementsByClassName("demo")[0];
    var a = l.children;
    var arry = [...a];
    var r=arry.shift();
    console.log(r);
</script>
大家讲道理

Of course, shift is an array method. You can convert the class array into an array first and then call it
Array.prototype.slice.call(arraylike);

学霸

console.log(a)
You can see: __proto__:HTMLCollection There is no shift method in HTMLCollection.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!