简体   繁体   English

使用JavaScript从数组中获取价值

[英]Get Value from Array using javascript

I am passing data into array from mysql query and getting it into javascript which is display like this 我正在将数据从mysql查询传递到数组中,并将其输入到显示如下的javascript中

Data:{"0":[{"Question":"abc","Answer":"abc 123"},{"Question":"xyz","Answer":"xyz 123 "}], "message":"Success"} 数据:{“ 0”:[{“ Question”:“ abc”,“ Answer”:“ abc 123”},{“ Question”:“ xyz”,“ Answer”:“ xyz 123”}]“,” message“ :“成功”}

Now I want to get all Question in one variable and related FAQ_Answer in another variable and display like 现在,我想在一个变量中获取所有问题,并在另一个变量中获取相关的FAQ_Answer,并显示如下

Question : abc Answer : abc 123 问题:abc答案:abc 123

Question : xyz Answer : xyz 123 问题:xyz回答:xyz 123

But the problem is that I don't know how to get related question and its answer from an array. 但是问题是我不知道如何从数组中获取相关问题及其答案。

I tried all the methods like data[0][0] or etc. but it is giving me undefined or [object,object] type of output. 我尝试了所有方法,例如data [0] [0]等,但这给了我未定义的或[object,object]类型的输出。

You need to read some documentation about javascript syntax a little :p . 您需要稍微阅读一些有关javascript语法的文档:p。

In this case, let's assume you have =: 在这种情况下,假设您有=:

var data = {"0":[{"Question":"abc","Answer":"abc 123"}]};

It is read like this: data is an object, containing a single key named "0", which is a reference to an array. 读取方式如下:data是一个对象,包含一个名为“ 0”的键,该键是对数组的引用。 The array contains a single entry. 该数组包含一个条目。 That entry is an object containing 2 keys, "Question" and "Answer", each being a string. 该条目是一个包含2个键的对象,“键”和“答案”分别为字符串。

So, with that said: 所以,说:

data // is the object
data[0] // references the array of questions, note that it is in fact data["0"]
data[0][0] // references the first entry in the array of questions
data[0][0].Question // contains the first question's text
data[0][0].Answer // contains the first question's answer

Typically, you'd make a variable that represents what your dealing with to make it clear to whoever reads the code, eg 通常,您将创建一个变量来表示您要处理的内容,以使任何人都可以清楚地阅读代码,例如

var first_question = data[0][0];

and use the properties from then on. 并从那时起使用这些属性。

Here's how it can be done: 这是可以完成的方法:

var data = {Data:{"0":[{"Question":"abc","Answer":"abc 123"},{"Question":"xyz","Answer":"xyz 123 "}], "message":"Success"}};
var qaList = data.Data['0'];

// build HTML in div from questions and answers
var div = document.getElementById('qa');
for (var i = 0; i < qaList.length; ++i) {
    var qa = qaList[i];
    div.innerHTML += 'Question : '+qa.Question+' Answer : '+qa.Answer+'<br/>';
} // end for

http://jsfiddle.net/61uv7jnj/ http://jsfiddle.net/61uv7jnj/

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

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