我怎样才能在javascript中添加?

时间:2018-05-03 16:56:40

标签: javascript ajax

首先,我将陈述明显的,我是javascript,html和web开发工具的新手。

var labels = {{ labels|tojson|safe }};

使用console.log我能够看到标签console.log(JSON.stringify(labels));的内容 输出:

[
    {"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},
    {"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},
    {"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},
    {"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}
]

它显然是一个字典列表,到目前为止一直很好,现在有新的元素我想在它运行时附加并且没有刷新页面手动,它应该自动更新,所以因为我有一些经验python,我很快想到了追加,就像那样:

labels.append({"id":labels.length + 1, 
               "name":"",
               "xMin":xMin,
               "xMax":xMax,
               "yMin":yMin,
               "yMax":yMax
              })

但它不起作用,我该怎么追加那条线?

2 个答案:

答案 0 :(得分:2)

labels是一个数组类型,因为它有

[{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}]

因此,您需要使用labels.push(obj)labels而非append()

中添加新对象

var labels = [{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}]

var xMin = 1, xMax = 5, yMin = 3, yMax = 8;

labels.push({"id":labels.length + 1, "name":"", "xMin": xMin, "xMax":xMax, "yMin":yMin, "yMax":yMax});

console.log(labels);

答案 1 :(得分:2)

Array.prototype.append()不存在。如果要添加Array.prototype.push(),则需要使用var labels = [{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}]; console.log(labels); labels.push({"id":labels.length + 1, "name":"name", "xMin":'xMin', "xMax":'xMax', "yMin":'yMin', "yMax":'yMax'}); console.log(labels);

像这样:



select
  *
from
  artists as a
where
  exists (
    select
      *
    from
      event_artist as ea
    where
      ea.artist_id = a.id
  )