简体   繁体   English

将单个类型为字符串的元素的数组“神奇地”转换为字符串

[英]Array with single element of type string “magically” turning into string

Not sure why this is happening. 不知道为什么会这样。 At this point in my code these array may have a single element. 在我的代码中,这些数组此时可能只有一个元素。

actualAnswer = actualAnswer.split(" ");
playerAnswer = playerAnswer.split(" ");

I then pass them through this function. 然后,我将它们通过此函数传递。

     function checkForPlural(playerAnswer, actualAnswer){

var answerObject = {playerAnswer: playerAnswer,
                    actualAnswer: actualAnswer};

for (var answerWord in actualAnswer){
    if (actualAnswer[answerWord].slice(-1) == "S")
    {
            answerObject.actualAnswer[answerWord] = actualAnswer[answerWord].substring(0, actualAnswer[answerWord].length - 1);
    }
}
for (var answerWord in playerAnswer){
    if (playerAnswer[answerWord].slice(-1) == "S")
    {
            answerObject.playerAnswer[answerWord] = playerAnswer[answerWord].substring(0, playerAnswer[answerWord].length - 1);
    }
}
}

When I return the object IF the array's passed in only had a single element javascript decides to interpret them as a string so if I were to use answerObject.actualAnswer.length it'll give me the length of the string, rather than just 1. 当我返回对象IF时,传入的数组只有一个元素,javascript决定将其解释为字符串,因此,如果我使用answerObject.actualAnswer.length,它将为我提供字符串的长度,而不是1。

Here is the plunker, unfortunately/fortunately it seems to work as intended on there so i'm confused: https://plnkr.co/edit/nIqq3VdjjMa2GDWyqkxx 这是the子,不幸的是,不幸的是,它似乎按预期的那样工作,所以我很困惑: https ://plnkr.co/edit/nIqq3VdjjMa2GDWyqkxx

EDIT: The problem was at an earlier junction in my code, sorry! 编辑:问题出在我的代码中较早的交界处,抱歉!

You can use Array.prototype.map() to return a new array, String.prototype.replace() to, if exists, replace the ending "S" character in a string, return an object having properties set to the function parameter identifiers 您可以使用Array.prototype.map()返回一个新数组String.prototype.replace() ,如果存在,则替换字符串中的结尾"S"字符,返回一个对象,该对象的属性设置为函数参数标识符

 const regexp = /S$/; const re = ""; function parseAnswer(arr, regexp_, re_) { return arr.map(function(prop) {return prop.replace(regexp_, re_)}) } function checkForPlural(playerAnswer, actualAnswer) { return { playerAnswer: parseAnswer(playerAnswer, regexp, re), actualAnswer: parseAnswer(actualAnswer, regexp, re) } } console.log(checkForPlural("abc defS ghi".split(" "), "12S 456 78S".split(" "))) 

The code in question is working correctly, the "magic" conversion was because of an error in another function that was overwriting the array with a string. 有问题的代码正常工作,“魔术”转换是由于另一个函数的错误,该函数用字符串覆盖了数组。 My bad. 我的错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM