gpt4 book ai didi

forEach 中的 JavaScript 三元运算符返回未定义

转载 作者:行者123 更新时间:2023-11-27 23:55:33 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数接受一个字符串并将“minorWords”字符串中未包含的每个单词的第一个字母大写。我的代码中缺少什么导致返回值“未定义”?在用几种不同的方式编写这个函数之后,我现在认为我只是错误地使用了 .forEach 。我相当确定我正确使用了三元运算符,但我尝试替换 if 语句并得到相同的结果( undefined )。我也不确定为什么 undefined 被返回两次。 。 .

function titleCase1(title, minorWords) {
var titleArray = title.split(" ");
var minorArray = minorWords.split(" ");
var newArray = titleArray.forEach(function(word){
(word in minorArray)? word :
word[0].toUpperCase() + word.slice(1);
})
console.log(newArray);
}

titleCase1("the wind in the willows", "the in");
// -> undefined undefined

我意识到,如果这有效,第一个“the”将不会大写,但一旦我不再滥用这里的工具,我就会弄清楚这一点。 。 .

最佳答案

您的代码有两个问题:

  1. 唯一的东西forEach所做的是对数组中的每个元素执行回调并且不返回任何内容,因此 newArray永远是undefined 。供引用检查如何 forEach作品here

    如果您想创建一个新数组,其值类似于您尝试使用 newArray 执行的操作。您需要使用map ,但实际上您需要从回调中返回一个值。供引用检查如何 map作品here .

  2. 您不能使用 in运算符来查看数组中是否存在单词。 in运算符仅检查指定对象中是否存在指定属性。因此它总是返回 false当用于检查数组内部的元素时。 因为 javascript 中的数组实际上是底层的对象!

    var a = [ 'A', 'b', 'C'];

    实际上是

    var a = { 0: '一', 1: 'b', 2:“c”};

    因此'a' in [ 'a', 'b', 'c' ]将始终返回 false例如0 in [ 'a', 'b', 'c' ]将返回true .

    由于这个警告,您应该改变您的方法,例如使用 indexOf 。供引用检查如何 indexOf作品here .

考虑到这一点,您可以将代码修改为以下内容以获得所需的行为:

function titleCase1(title, minorWords) {
var titleArray = title.split(' ');
var minorArray = minorWords.split(' ');
var newArray = titleArray.map(function (word) {

// indexOf returns the elements index on match or -1.
var match = minorArray.indexOf(word) != -1;

// If there's a match, return the (lowercased) word, otherwise uppercase it.
return match ? word : (word[0].toUpperCase() + word.slice(1));
});

console.log(newArray);
}

titleCase1("the wind in the willows", "the in"); // [ 'the', 'Wind', 'in', 'the', 'Willows' ]

关于forEach 中的 JavaScript 三元运算符返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32297875/

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