[英]Chaining Methods error in Javascript
I would like to know the reason why this simple piece of code fails: 我想知道这段简单的代码失败的原因:
var arr = [1, 2, 3];
arr.push(arr[0]).shift();
console.log(arr);
it returns in firebug console "TypeError: arr.push(...).shift is not a function" 它在Firebug控制台中返回“ TypeError:arr.push(...)。shift不是函数”
I think it happens because I invoke the shift() method not on an array but on the pushed element. 我认为这是因为我不是在数组上而是在push元素上调用了shift()方法。
Is there a more elegant way to obtain the same result that, 有没有更优雅的方式来获得相同的结果,
var arr = [1, 2, 3];
arr.push(arr[0]);
arr.shift();
console.log(arr);
produce ? 生产 ?
Thanks in advance! 提前致谢!
The push() method adds one or more elements to the end of an array and returns the new length of the array. push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。
arr.push(arr[0])
doesn't return the array but a number which, obviously, has no shift
function. arr.push(arr[0])
不返回数组,而是一个显然没有shift
函数的数字。
To my knowledge, there's no simple expression pushing an element to an array and returning that array. 据我所知,没有简单的表达式将元素推到数组并返回该数组。 But in your case you may simply reverse the operations and do 但是根据您的情况,您可以简单地反转操作并执行
arr.push(arr.shift());
I think it happens because I invoke the shift() method not on an array but on the pushed element. 我认为这是因为我不是在数组上而是在push元素上调用了shift()方法。
Almost. 几乎。 push
returns the new length of the array. push
返回数组的新长度。 A number obviously doesn't have a shift()
method. 一个数字显然没有shift()
方法。
Your method of putting it on two lines is the simplest way. 将其放在两行上的方法是最简单的方法。
Essentially this question is saying, can I somehow "elegantly" express the notion of moving the first item of an array to the end. 本质上,这个问题是在说,我能以某种方式“优雅地”表达将数组的第一项移到末尾的想法。 Luckily, JS is a Turing-complete language, which allows us to define functions, so the "elegant" answer is just 幸运的是,JS是一种图灵完备的语言,它使我们能够定义函数,因此“优雅”的答案仅仅是
rotate(arr)
Now it merely remains to define rotate
. 现在只剩下定义rotate
。 To rotate is to drop the first element in the result of adding the head element to the end: 旋转是在将 head元素添加到末尾的结果中删除第一个元素:
function rotate(arr) { return drop(add(arr, head(arr))); }
Now drop
is 现在drop
是
function drop(arr) { return arr.shift(), arr; }
and head
of course is 当然是head
function head(arr) { return arr[0]; }
and add
is 并add
是
function add(arr, elt) { return arr.push(elt), arr; }
I could also write a function to move n
elements from position i
to position j
, using splice
, as follows: 我还可以编写一个函数,使用splice
将n
元素从位置i
移动到位置j
,如下所示:
function move(arr, n, i, j) {
arr.splice.apply(arr, [j-n+1, 0].concat(arr.splice(i, n)));
return arr;
}
Then to rotate
is to move one element at the beginning to the end : 然后以rotate
是在起点到终点 移动一个元素:
function rotate(arr) { return move(arr, 1, 0, 999); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.