我可以将 forEach 方法添加到 Array 原型的 String 原型吗?

Can I add forEach method to String prototype from Array prototype?

我们知道 JavaScript 中有一个数组的 .forEach() 方法。但是字符串没有内置该方法。

那么,下面的代码片段有没有问题: String.prototype.forEach = Array.prototype.forEach ?

此设置帮助我将 .forEach 用于字符串。

let myName = "Avetik";   

String.prototype.forEach = Array.prototype.forEach;

myName.forEach(char => {

console.log(char);
})

上面的代码工作正常并输出我名字的所有字符。

你已经猜到我是JS新手了

.forEach() 本质上是数组(多个事物的组)的函数。一个字符串只有 1 个东西,当只有 1 个时,没有办法为“每个”做一些事情。

您可以在字符串上使用 .split() 将其转换为每个字符的数组。 然后对结果执行任何你想要的数组操作。 然后 .join() 在数组上将其转换回字符串,如果需要的话。

var myString = "beans";
var myArray = myString.split(); // this will be an array of 5 strings: ['b', 'e', 'a', 'n', 's']

可以,但是:

  • 这很令人困惑(在同一代码库上工作的其他开发人员在看到这样一个在字符串上调用的方法时可能会非常困惑)
  • 可能导致代码脆弱(如果定义String.prototype.forEach,它可能会干扰其他使用 String 原型方法的代码)
  • 帮助不大:你可以很容易地做到 [...str].forEach,你也可以很容易地做到 for (const char of str) {

// Say we want to iterate over this string:
const str = 'str';

// without adding a method to the prototype. Easy:

// One method:
for (const char of str) {
  console.log(char);
}

// Another method:
[...str].forEach((char) => {
  console.log(char);
});

  • 可以 如果有足够的脚本作者定义这样的东西(看看 Array.prototype.containsArray.prototype.flatten 发生了什么)

所以,这是可行的,但这可能不是一个好主意。

您可以添加自己的包装器...

我无法抗拒这种糟糕的想法!
我的建议是,去做吧,等待那一天,否则这样的做法会对你不利。然后你就会有这样一个错误的衡量标准,我希望这一定会阻止你玩语言语法,运气好的话你可能会成为一名计算机语言大师。

if(typeof String.prototype.forEach !== "function") {
  String.prototype.forEach = Array.from(this).forEach
};

// sample usage :
let abc = 'abc'

abc.forEach((letter, index)=> console.log(letter,index))

but it would be better to use a less ambiguous name

if(typeof String.prototype.forEachLetter !== "function") {
  String.prototype.forEachLetter = Array.from(this).forEach
};

// sample usage :
let abc = 'abc'

abc.forEachLetter((letter, index)=> console.log(letter,index))