当我直接使用和通过变量使用它们时,为什么split()和shift()会产生不同的结果

时间:2019-02-26 06:24:29

标签: javascript

我很难理解一件事。

假设我们有一个 const text = "little text test"

当我使用 console.log(text.split(' '))

控制台返回一个数组,其中包含3个元素“ little”,“ text”和“ test”。直到这里还可以

所以如果我用 const test = text.split(' ') ,然后 console.log(test) 控制台返回一个包含2个元素“文本”和“测试”的数组,这在我的脑海中毫无意义

当我尝试使用shift()时也会发生同样的情况,如果我使用 log.console(test.shift()) ,则控制台返回文本及其右侧,剪切数组中的第一项,然后带给我下一个< / p>

但是如果我使用 const test2 = test.split(' ') ,则 log.console(test.shift()) 控制台返回的内容很少,但是shift()删除了数组的第一个参数...那为什么我少了?

代码:

const text = "little text test";
const test = text.split(' ');
const test2 = test.shift();
console.log(text.split(' '));
console.log(test);
console.log();
console.log(test.shift());
console.log(test2);

控制台:

[ 'little', 'text', 'test' ]
[ 'text', 'test' ]

text
little

1 个答案:

答案 0 :(得分:2)

您对shift方法有错误的认识。 Array.prototype.shift() 会执行以下操作:

1。它会改变数组。

const a = [1,2,3]
a.shift();
console.log(a) // [2,3]

2。它返回移位后的元素。

const b = [1,2,3].shift();
console.log(b) // 1

所以,您看到的是JS的自然行为。

const text = "little text test";
const test = text.split(' ');
const test2 = test.shift(); // this line mutate the test array.
console.log(text.split(' '));
console.log(test);
console.log();
console.log(test.shift());  // this line, too. And it prints shifted one, not the whole elements.
console.log(test2);         // test2 holds 'little' string by line 3.