简体   繁体   English

检查对象文字属性的名称

[英]check the name of an object literal property

I have a shorthand function for element creation that takes a tag name and an object literal. 我有一个用于元素创建的简写函数,该函数带有标签名和对象文字。

//create element
function $make(tag, parameters) {
    var o = document.createElement(t);
    if (p.style) o.style.cssText = p.style;
    if (p.class) o.className = p.class;
    if (p.text) o.textContent = p.text;
    return o;
}

You call it simply enough: 您可以简单地称呼它:

var e = $make('div', {style: 'float: left', class: 'myClass', text: 'Some Text'});

Instead of setting a check for each individual attribute, I'd like to set attributes using a key character prefix in the property. 我不想为每个单独的属性设置检查,而是想使用属性中的键字符前缀来设置属性。 For instance, if I wanted to set href for a link, I might call: 例如,如果我想为链接设置href ,我可以调用:

var e = $make('a', {style: 'float: left', text: 'Google', ~href: 'https://www.google.com'});

How can I iterate through the properties of an object literal and check whether the name of the property itself ( not the value) starts with a specific character or string? 如何遍历对象文字的属性并检查属性本身的名称( 而不是值)是否以特定的字符或字符串开头? Is this even possible? 这有可能吗? If not, what would you recommend as an alternative? 如果没有,您会推荐什么替代方案?

You can use a for...in loop to get each key in the Object , and then check for the existence of the string or character. 您可以使用for...in循环获取Object每个键,然后检查字符串或字符是否存在。

In the example below, I am checking to see that the key starts with the "~" character. 在下面的示例中,我正在检查键是否以“〜”字符开头。

for (const key in myObject) {
    if (key.indexOf('~') === 0) {
        // key contains '~' character
    }
}

you could also use regex to match a string, instead of using indexOf 您还可以使用正则表达式来匹配字符串,而不是使用indexOf

Instead of for...in I'd suggest using a forEach loop over the Object.keys function. 而不是for ...我建议在Object.keys函数上使用forEach循环。 This is because for ... in looks up the prototype chain ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Iterating_over_own_properties_only ). 这是因为for ... in查找原型链( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Iterating_over_own_properties_only )。

var obj = {"style": 'float: left', "text": 'Google', "~href": 'https://www.google.com'};
Object.keys(obj).forEach((elm) => {
  console.log("Key=>Value : " + elm + "=>" + obj[elm]);
  if(elm.contains("~")) {
    console.log("Key: " + elm + " contains ~");
  }
});

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

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