gpt4 book ai didi

javascript - 我们可以在任何地方使用 `const` 而不是 `let` 吗?

转载 作者:行者123 更新时间:2023-11-28 13:14:03 24 4
gpt4 key购买 nike

对于flowtype,我们更喜欢const而不是let

我有需要以最高效的方式工作的函数,它对我来说效果很好,它比较两个数组,所以这是我的问题的一个很酷的例子:

/**
* @function compare
* @description function compares two arrays with ids to figure out: are they equal? (elements position can be different)
* @param arraFrom {Array}
* @param arraTo {Array}
* @param compareFunction {Function}
* @returns {Boolean}
*/
function compare(arraFrom, arraTo, compareFunction) {
let notEqual = true;
if(arraFrom.length !== arraTo.length) return false;
for (let i = 0; i < arraFrom.length; i++) {
notEqual = true;
for (let j = 0; j < arraTo.length; j++) {
if (compareFunction ?
compareFunction(arraFrom[i], arraTo[j]) :
arraFrom[i] === arraTo[j]) {
notEqual = false;
break;
}
}
if (notEqual) return false;
}
return true;
}

问题是:在不使用 let 的情况下,我们如何以最高效的方式实现它?

谢谢!

最佳答案

您可以使用 for...of 循环,而不是通过改变索引变量来迭代数组:

function compare(arraFrom, arraTo, compareFunction) {
let notEqual = true;
if(arraFrom.length !== arraTo.length) return false;
for (const a of arraFrom) {
notEqual = true;
for (const b of arraTo) {
if (compareFunction ? compareFunction(a,b) : a === b) {
notEqual = false;
break;
}
}
if (notEqual) return false;
}
return true;
}

您可以简单地提前返回,而不是使用可变的 notEqual 标志:

function compare(arraFrom, arraTo, compareFunction) {
if (arraFrom.length !== arraTo.length) return false;
outer: for (const a of arraFrom) {
for (const b of arraTo) {
if (compareFunction ? compareFunction(a,b) : a === b) {
continue outer;
}
}
return false;
}
return true;
}

但这非常难以理解。我建议使用以下内容:

function compare(arrayFrom, arrayTo, compareFunction) {
if (arrayFrom.length !== arrayTo.length) return false;
const test = typeof compareFunction == "function"
? a => b => compareFunction(a, b)
: a => b => a === b;
return arrayFrom.every(a => arrayTo.some(test(a)));
}

关于javascript - 我们可以在任何地方使用 `const` 而不是 `let` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40108550/

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