gpt4 book ai didi

javascript - apply 方法不在 javascript 中返回完整的数组值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:34 25 4
gpt4 key购买 nike

我在 apply 方法中创建了一个要传递的数组,我期望返回数组的完整值,但是当我使用数组的索引值来给出该索引的值时,数组方法实际上返回了字符的索引:

var obj = {
name: 'Dogs'
}
var arr = ['India', 'Slovenia', 'Scotland'];

var getanimalsinfo = function(a) {

return this.name + ' is good animal found in ' + a[2]

}
console.log(getanimalsinfo.apply(obj, arr));

在这里,我期待“Dog is good animal found in Scotland”,但我得到:“Dog is good animal found in d”。 这里d是印度的第三指数。请让我知道我做错了什么。谢谢。

最佳答案

.apply 将数组的每个元素作为单独的参数传递给函数。 IE。在您的情况下,该函数被称为 getanimalsinfo(arr[0], arr[1], arr[2]) 因此 a 将具有值 '印度”

如果您想将数组作为单个参数传递(相当于 getanimalsinfo(arr)),请改用 .call:

var obj = {
name: 'Dogs'
}
var arr = ['india', 'slovenia', 'scotland'];

var getanimalsinfo = function(a) {

return this.name + ' is good animal found in ' + a[2]

}
console.log(getanimalsinfo.call(obj, arr));
// ^^^^

替代解决方案:

  • 将传递给 .apply 的参数包装在另一个数组中:getanimalsinfo.apply(obj, [arr])
  • 使用 rest parameter在您的函数定义中:function(...a) {/*...*/}

查看 MDN 文档以获取更多信息:

相关:

关于javascript - apply 方法不在 javascript 中返回完整的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53646991/

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