gpt4 book ai didi

javascript - 对象/数组方法 : Modify original or create new? 指南

转载 作者:行者123 更新时间:2023-11-30 05:36:00 25 4
gpt4 key购买 nike

对于 javascript,我们有像 filtermap 这样的方法,它们不会修改原始数组,而是根据提供的函数创建一个新数组。

我们还有像 sort 这样的方法来修改原始数组。

以上是 ECMA 标准的一部分示例。

我还看到库或 GIST 中的定制函数不符合任何标准或最佳实践。

shuffle 这样的事情,通常使用像 Fisher–Yates 这样的算法,90% 的时间修改原始数组,但偶尔会创建一个新数组。

compress 这样的方法可以去除数组中的 holes,同样经常修改原始数组,但有时会创建一个新数组。

因此,在调查 uniqueremoveDuplicates 时,我遇到了 3 种可能性。

function unique(array) {
create newArray;
push unique values into newArray;
return newArray;
}

上面创建了一个新的唯一值数组,保持原始数组不变。

function unique(array) {
remove duplicates from original array;
return array;
}

上面修改了原始数组并返回了对原始数组的引用。

function unique(array) {
create removedArray;
remove duplicates from original array and push the removed elements into removedArray;
return removedArray,
}

上面和前面的类似,只是记录了被移除的元素并返回给我,有点像splice

这一切让我想知道在创建适用于对象或数组的方法时是否有任何标准或最佳实践?

我还没有找到,它们存在吗?

如果不是,那么我知道这个问题可能会导致基于意见的答案,但这似乎是一个明智的问题?

最佳答案

The ECMAScript Language Specification 5.1 (2011)没有概述为什么有些方法会修改原始对象而有些方法不会。

作为示例,它仅概述了 Array.prototype.map ( 15.4.4.19 )

map does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.

没有具体说明为什么会这样。

但是,对于确实修改了原始对象的方法,除了对该方法的一般描述外似乎没有特别说明。 Array.prototype.sort ( 15.4.4.11 ) 的定义示例:

The elements of this array are sorted. [Rest of the definition follows.]

总结一下:
在原始对象被修改的情况下,对其进行明确说明,而在原始对象修改的情况下,不添加特别通知。因此,似乎有一个隐含的标准,即此类方法修改原始对象,但没有明确的协议(protocol)或规范。

关于javascript - 对象/数组方法 : Modify original or create new? 指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com