数组上的 JavaScript 头和尾没有变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35361225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:38:09  来源:igfitidea点击:

JavaScript head and tail on array without mutation

javascriptarrays

提问by Knows Not Much

I found about JavaScript array operations Unshift, shift, push, pop

我发现了 JavaScript 数组操作 Unshift、shift、push、pop

However all these operations mutate the array.

然而,所有这些操作都会改变数组。

Is there a way I could use these functions without causing mutation on the original data?

有没有一种方法可以使用这些函数而不会导致原始数据发生突变?

Somehow I feel that reading the data should not cause mutation.

不知怎的,我觉得读取数据不应该引起突变。

回答by Davin Tryon

You can use:

您可以使用:

var head = arr[0];
var tail = arr.slice(1);

Or in ES6:

或者在 ES6 中:

const [head, ...tail] = arr;

回答by Suhail Mumtaz Awan

I would do using ES6 as below

我会使用 ES6 如下

const head = ([h]) => h;
const tail = ([, ...t]) => t;

const arr = [1,2,3,4,5];

alert(head(arr));

回答by Bamieh

The accepted answer is good, but for a more functional approach:

接受的答案很好,但对于更实用的方法:

Heads

I'd use find, which returns the first element that returns a true-thy value in its predicate.

我会使用 find,它返回第一个在其谓词中返回真值的元素。

If you are sure your values are true-thy, you can write it as follows:

如果你确定你的价值观是真实的,你可以这样写:

arr.find(Boolean)

If you want the first value, regardless of its value, you can write it as follows:

如果你想要第一个值,不管它的值是多少,你可以这样写:

arr.find(_ => true)

Tails

尾巴

Just as the others state, use slice

正如其他人所说,使用 slice

arr.slice(1);