Javascript:如何使用push方法?

时间:2017-09-08 12:07:57

标签: javascript arrays

我有一个问题,我试图解决,我正在努力。 有人可以解释一下下面的代码如何工作,我读了不同的数组方法,但仍然无法解决下面的问题。谢谢。

it('should add elements at the end of the array with the push method', function () {
    var nums = [1,2,3];
    // every array has a method called 'push'
    // It is a function that accepts as its first argument a value
    // The passed value gets added to the array at the end (last position)
    nums.push(4);
    expect(nums).toEqual();
    expect(nums.length).toEqual();
    // Note that we don't save what push returns, we just call it.
    // Push has the side effect of adding a value to the array, but it doesn't return the new array
    // What do you think it returns?
    var pushResult = nums.push();
    expect(nums.length).toEqual();
    expect(pushResult).toEqual();
    var pushResult = nums.push('hello');
    expect(nums.length).toEqual();
    expect(pushResult).toEqual();
  });

5 个答案:

答案 0 :(得分:0)

push()方法将新项添加到数组的末尾,并返回新的长度。

W3Schools Documentation

Mozilla Documentation

答案 1 :(得分:0)

var arr = [
    "ehy",
    "you",
    "Ciao"
];


console.log(arr.push("riciao"));

console.log(arr);

答案 2 :(得分:0)

this将新项目/项目添加到数组的末尾。

实施例

push()

var numbers = [1, 2, 3, 4]; numbers.push(5); 的结果将是:

numbers

答案 3 :(得分:0)

var array=[1,2,3,4,5];
array.push(6);
array.push(7,8);
8
array
(8) [1, 2, 3, 4, 5, 6, 7, 8]
array.push({name:'Hello',operation:'push me as an object'});
9
array
(9) [1, 2, 3, 4, 5, 6, 7, 8, {…}]0: 11: 22: 33: 44: 55: 66: 77: 88: {name: "Hello", operation: "push me as an object"}length: 9__proto__: Array(0)

答案 4 :(得分:0)

此代码是单元测试的一部分 您需要在代码中进行更改以传递断言 例:

var nums = [1,2,3];
nums.push(4);
expect(nums).toEqual([1,2,3,4]);  // true