我想为'myObj'添加一个新属性,将其命名为'string1'并赋予它'string2'的值,但是当我这样做时它会返回'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
Run Code Online (Sandbox Code Playgroud)
换句话说:如何创建一个对象属性并为其赋予存储在变量中的名称,而不是变量本身的名称?
classList我正在根据变量\xe2\x80\x99s 的真实性从元素\xe2\x80\x99s 添加/删除一个类。然而,我\xe2\x80\x99m 这样做似乎是一种迟钝的方式:
if (myConditionIsMet) {\n myEl.classList.add("myClass");\n} else {\n myEl.classList.remove("myClass");\n}\nRun Code Online (Sandbox Code Playgroud)\n有没有一种方法可以让这个更性感并动态调用add/remove链式函数,例如使用条件运算符,例如:
myEl.classList.{myConditionIsMet ? add(\'myClass\') : remove(\'myClass\')};\nRun Code Online (Sandbox Code Playgroud)\n当然,上面是伪代码,我希望尽可能简单的 JS。
\n我循环遍历jQuery选择器并尝试将表单元素的值分配给容器变量,然后可以将其作为JSON传递给进一步的操作.
假设有三组复选框,每组都在自己的div中,名为group1,group2和group3.
这是伪代码,但是像这样:
var data = {};
var groups = {
'group1': obj with a bunch of key val pairs for checkboxes,
'group2': another obj,
'group3': and another obj
}; // these define divs / groups of checkboxes
// create all the checkboxes and divs from the groups object somewhere in here
//now build a function to loop over the groups and get any checked boxes
function getInputs(){
$.each(groups, function(index, el) {
// this is where I am stuck
data.index …Run Code Online (Sandbox Code Playgroud) var jsonObj = [
{
"key1": "value1",
"key2": "value2",
"key3?": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3?": "value3"
}
];
Run Code Online (Sandbox Code Playgroud)
我想更新所有对象的所有值。这里的键和值是动态的,而不是 key1 和 value1。你能帮忙弄清楚它的要求吗?
我想让每个对象的每个值都变成“changedvalue”。所以更新jsonObj后的最终结果是
[
{
"key1": "changedvalue",
"key2": "changedvalue",
"key3?": "changedvalue"
},
{
"key1": "changedvalue",
"key2": "changedvalue",
"key3?": "changedvalue"
}
];
Run Code Online (Sandbox Code Playgroud)