JavaScript -为什么推送不工作并抛出异常
JavaScript - why the push is not working and throwing exceptions?
我怎么能有pc。Id和pc。保持现有PC的原样来增加数量?执行以下操作无法获得异常
//Example Python pc_config is assigned to pc : var pc = {{ pc_config | safe }};
function createPeerConnection() {
try {
var element = {};
element.id = 'test001';
element.quantity = '30';
pc.push(element);
console.log(JSON.stringify(pc));
// i want to have : pc.id or pc.quantity without losing the default values already
// pc was assigned by Python
} catch (e) {
console.log("FAIL");
return;
}
}
push只存在于数组
你可以直接添加元素,如果你想要pc。身份证,pc.quantity
pc.id = element.id;
pc.quantity = element.quantity;
或者如果您想将其用作数组,请检查jsfiddle: http://jsfiddle.net/Fe9Z3/
在本例中,我定义了一个push函数到pc,它检查你最新的索引器,并添加一个新元素。你应该只添加一次push到pc,在你初始化它的值之后。
function jsonNormal() {
var el = document.getElementById('json_normal');
var pc = {};
pc.push = function(val) {
var i = 0;
while (typeof pc[i] !== 'undefined') {
i++;
}
pc[i] = val;
};
var element = { id: 'test', quantity: 30 };
var element2 = { id: 'test2', quantity: 40 };
pc.push(element);
pc.push(element2);
el.innerHTML = JSON.stringify(pc);
}
这个例子使用了一个数组的原型函数,它需要在你的pc元素中有一个属性长度,然后push函数被添加到你的对象中(同样,只添加一次:))
function jsonArray() {
var el = document.getElementById('json_push_array');
var pc = {length:0};
pc.push = Array.prototype.push.bind(pc);
var element = { id: 'test', quantity: 30 };
var element2 = { id: 'test2', quantity: 40 };
pc.push(element);
pc.push(element2);
el.innerHTML = JSON.stringify(pc);
}
基于注释更新
这只会留下最近的推送,当第二次添加没有定义id时,第一个id可能仍然存在(但是你可以确保id至少在元素上定义为null)
Jsfiddle update: http://jsfiddle.net/3ULy8/
pc.push = function(val) {
if (typeof val === 'undefined' || !val) {
return;
}
for (var i in val) {
if (!val.hasOwnProperty(i)) {
continue;
}
pc[i] = val[i];
}
};
只能push到Array中。只需在声明函数之前添加这一行。
var pc = [];
function createPeerConnection() {
.....
相关文章:
- 为什么浏览器没有为语法错误抛出异常
- PHP REST服务抛出异常——希望避免控制台错误
- 测试抛出异常的函数
- (为什么)我不能从生成器中抛出异常吗
- 如何抛出异常
- 抛出异常:Node.js与Gevent
- 当请求DOM对象时,XMLHttpRequest.send()抛出异常
- AngularJS在尝试轻松保存Changes时抛出异常
- $mdDialog.prompt 抛出异常,但该函数在确认时工作正常
- 在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否昂贵
- 自定义抛出异常JavaScript的错误消息
- 在网格弹出编辑器中上传剑道:如何防止上传抛出异常时窗口关闭
- 在原型方法中抛出异常,未在外部尝试捕获 (JavaScript) 中捕获
- XSLT 2.0 错误处理:向 JavaScript 抛出异常
- 为什么抛出异常后不再被视为已发生
- 对于角度为2的循环抛出异常
- Angular Service在返回promise时抛出异常
- mark.setDragable(false)在API谷歌地图的main.js中抛出异常
- 谷歌图表在不抛出异常的情况下无法工作
- JavaScript -为什么推送不工作并抛出异常