我想要制作一个模仿'a' in 'abc'语法的JS原型函数。
它按照第一个示例中的预期工作,但在第二个示例中不起作用。我做错了什么?
String.prototype.in = function(input) {
return input.indexOf(this) > -1
}
console.log('a'.in('abc'))
// equivalent of 'abc'.indexOf('a') > -1
// true
console.log('a'.in(['a']))
// equivalent of ['a'].indexOf('a') > -1
// false
发布于 2019-07-26 22:09:23
原语值,如数字、字符串等。无法在javascript中使用方法。
因此,每当调用基元上的方法时,它都会被强制转换为其对象形式。
(类似于java或c#等语言中的“装箱”)
举例说明两者之间的差别:
// number primitive
let primitive = 12;
console.log(primitive);
// number object
let object = new Number(12);
console.log(object);
原语的对象形式大多与它们的原语反部分的行为方式相同,但是有几个区别,例如相等:
console.log(12 == 12); // true
console.log(new Number(12) == new Number(12)); // false
// mixed comparisons
console.log(new Number(12) == 12); // true (boxed value will be unboxed)
console.log(new Number(12) === 12); // false (strict equality)
第二个示例'a'.in(['a'])不能工作的原因是,Array.prototype.indexOf将检查每个元素是否严格相等(===)。
this字符串当前以其对象形式存在,但数组中的'a'以其基本形式存在-因此它们是而不是相等。
为了使in()函数正常工作,您需要“打开”字符串值。
您可以通过使用Object.prototype.valueOf()方法来这样做,该方法将返回原语值:
String.prototype.in = function(input) {
return input.indexOf(this.valueOf()) > -1
}
console.log('a'.in('abc')); // true
console.log('a'.in(['a'])); // true
https://stackoverflow.com/questions/57227345
复制相似问题