2

My aim is to add a JSON object based on certain conditions to an array which is then to be used to construct a WINJSList. I'm really struggling with accessing the elements of the list OR array after I have used the array.push method. I wanted to access these elements to ensure I am doing the addition right. Any help would be greatly appreciated. I have the following code

var names_Array = new Array;                
var names_List = new WinJS.Binding.List(names_Array);

if (condition) {
  if (condition) {
    names_List.push({ 
      name: "Joe Dowling", 
      image: "image/Joe Dowling.png", 
      ClientID: "1234" 
    });
  } else if (condition) {
    names_List.push({
      name: "Esteban Flamenco ", 
      image: "image/Esteban Flamenco.png", 
      ClientID: "6666" 
    });
  } else if (condition) {
    names_List.push({ 
      name: "Plain Jane ", 
      image: "image/Plain Jane.png", 
      ClientID: "0000" 
    });
                        }
console.log(names_Array);
console.log(names_Array[0]);
console.log(names_List);
console.log(names_List[0]);

I also tried:

var names_Array = new Array; 
if (condition) { 
  if (condition) {
    names_Array.push({
      name: "Joe Dowling", 
      image: "image/Joe Dowling.png", 
      ClientID: "1234" 
    });
  } else if (condition) {
    names_Array.push({
      name: "Esteban Flamenco ", 
      image: "image/Esteban Flamenco.png", 
      ClientID: "6666" 
    });
  } else if (condition) {
    names_Array.push({ 
      name: "Plain Jane ", 
      image: "image/Plain Jane.png", 
      ClientID: "0000" 
    });
  }

  var names_List = new WinJS.Binding.List(names_Array);

In the console I either get undefined or [object object]

4

2 回答 2

5

对于 WinJS.Binding.List,请参阅此处的文档。

代码有几个问题:

  • WinJS List 使用传递给构造函数的数组初始化自身。之后,如果修改了数组,则更改不会传播到 winjs 列表。
  • 要访问索引处的元素,请使用list.getAt(index)

这段代码应该可以工作:

var data = []; 
data.push({
    name: "Joe Dowling",
    image: "image/Joe Dowling.png",
    ClientID: "1234"
});
data.push({
    name: "Esteban Flamenco ",
    image: "image/Esteban Flamenco.png",
    ClientID: "6666"
        });
data.push({
    name: "Plain Jane ",
    image: "image/Plain Jane.png",
    ClientID: "0000"
});

var list = new WinJS.Binding.List(data);
var item = list.getAt(0);
console.info(JSON.stringify(item))
于 2013-05-29T10:58:11.540 回答
0

你让这比它应该做的更难这里是一个基于你正在使用的数据的简单示例:

var data = []; 
data.push({ 
      name: "Joe Dowling", 
      image: "image/Joe Dowling.png", 
      ClientID: "1234" 
    });
data.push({
      name: "Esteban Flamenco ", 
      image: "image/Esteban Flamenco.png", 
      ClientID: "6666" 
    });
data.push({ 
      name: "Plain Jane ", 
      image: "image/Plain Jane.png", 
      ClientID: "0000" 
    });


<!-- var item = data.getAt(0) -->
console.info(JSON.stringify(data))
console.info(JSON.stringify(data[0]))
var c = data[0];

for(var i in c){
    console.log(i); //key
    console.log(c[i]); //value
}
于 2015-08-30T22:03:38.427 回答