开发者

javascript - adding properties to array objects

I'm trying to loop through a pipe deli开发者_如何学Cmited list passed to a function, split it out into an array based on the pipe as a separator, and then break each item out into its component parts, where the format is as follows:

"76:1167|76:1168"

so that the array would be: surveyQuestions[0] = 76:1167. And then that would be split up into : surveyQuestions[0].question = 76 and surveyQuestions[0].answer = 1167.

And this is the code I'm using, but the values come back undefined when I try to add the properties to each array item.

function answerSurvey(survey){

var surveyResults = survey.split("|");

for (var i=0;i<surveyResults.length;i++){

    var surveyResult = surveyResults[i].split(":");
    var surveyQ = surveyResult[0];
    var surveyA = surveyResult[1];
    surveyResults[i].surveyQ = surveyQ;
    surveyResults[i].surveyA = surveyA;
    console.log(surveyResults[i].surveyQ + "|" + surveyResults[i].surveyA)
}

}

answerSurvey("76:1167|76:1168");


You are trying to add a property to a string, which you cannot do. If you want the Array to contain a list of Objects, use Array.map() to transform your strings into objects:

var surveyResults = survey.split("|").map(function (result) {
    var parts = result.split(":");
    return {
        question: parts[0],
        answer: parts[1]
    };
});

It is included in most browsers, but for older versions of some browsers, you'll need to add .map() manually.

Edit: jQuery does add a map function (as noted in the comments). Tweak the code above slightly to include the array as the first parameter to $.map() and substitute the argument name for this (or shift the result argument one to the right, following index):

var surveyResults = $.map(survey.split("|"), function (i, result) {
    var parts = result.split(":");  // or this.split(":")
    return {
        question: parts[0],
        answer: parts[1]
    };
});


Try this:

function answerSurvey(survey){

var surveyResults = survey.split("|");

for (var i=0;i<surveyResults.length;i++){

    var surveyResult = surveyResults[i].split(":");
    var surveyQ = surveyResult[0];
    var surveyA = surveyResult[1];
    surveyResults[i] = {};
    surveyResults[i].surveyQ = surveyQ;
    surveyResults[i].surveyA = surveyA;
    console.log(surveyResults[i].surveyQ + "|" + surveyResults[i].surveyA)
}

}

answerSurvey('76:1167|76:1168');


surveyResults[i] is a 'string' not an object, so you can't add properties to it.

Try this:

var surveyQ = surveyResult[0];
var surveyA = surveyResult[1];
surveyResults[i] = {};
surveyResults[i].surveyQ = surveyQ;
surveyResults[i].surveyA = surveyA;

Example: http://jsfiddle.net/Paulpro/WeJxe/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜