【发布时间】:2018-03-18 08:17:22
【问题描述】:
我正在尝试创建一个函数,如果字符串的结尾与给定变量相同,则返回该函数,而不使用 .endsWith()。
我不确定为什么这不起作用。链接 .join("") 并将两个值作为字符串进行比较,但不能作为数组。
const confirmEnding = (str, target) => {
// split string into array, splice end of array based on target length
console.log(str.split("").splice(str.length - target.length, target.length));
// split target into array
console.log(target.split(""));
// compare two arrays
return str.split("").splice(str.length - target.length, target.length) === target.split("");
console.log(confirmEnding("Congratulation", "on"));
输出
[ 'o', 'n' ]
[ 'o', 'n' ]
false
显然,数组是完全相同的。为什么布尔值返回 false?
【问题讨论】:
-
您不能比较两个具有相同内容但具有不同对象引用的数组。您需要比较项目。
-
您应该阅读这个问题stackoverflow.com/questions/7837456/… 及其答案
-
知道了,我不知道数组不能像原始数据类型那样进行比较。
-
一点帮助:
a = [1,2,3]; b = [1,2,3]; console.log(a === a); /* true */ console.log(a === b); /* false */:-)
标签: javascript arrays string boolean