简体   繁体   English

如果需要条件-测试属性是否存在(如果不存在),然后创建一个

[英]if condition needed - test if property exists if not then create one

Below is some code that overwrites a property in a string but what is missing in this function is a condition to test if the property exists and if it doesn't then create it and then return the whole string, otherwise overwrite the property and return then whole string which it does at the moment. 下面是一些代码,该代码将覆盖字符串中的属性,但是此函数中缺少的条件是测试该属性是否存在以及是否不存在然后创建它然后返回整个字符串的条件,否则将覆盖该属性然后返回目前正在执行的整个字符串。 I have attempted this but I'm not getting the desired result. 我已经尝试过了,但是没有得到想要的结果。 Can someone have a look and attempt to create a new property on the fly with the sample function below. 有人可以看看下面的示例函数来尝试动态创建新属性吗?

var cookieValue = 
   'id=1&state=normal&theme=purple:
    id=2&state=maximized&theme=pink:
    id=3&state=maximized&theme=black';

function setProperties(cookie, id , name, value, create) {
  var sections = $.map(cookie.split(":"), function (section) {
      var pairs;

      if (section.indexOf("id=" + id) === 0) {
          // if condition here - create a new property
          // else run code below
          pairs = $.map(section.split("&"), function (pair) {
              if (pair.indexOf(name + "=") === 0) {
                  return name + "=" + value;
              }else {                       
                  return pair;  
              }
          });

          return pairs.join("&");

      } else {
          return section;
      }
  });

  return sections.join(":");
}
alert(setProperties(cookieValue, '2', 'theme', 'green', true));
alert(setProperties(cookieValue, '2', 'color', 'orange', true)); // new property

Just remember if you have found the property: 请记住,如果您找到了该物业:

      if (section.indexOf("id=" + id) === 0) {
        // if condition here - create a new property
        // else run code below
        var found = false;
        pairs = $.map(section.split("&"), function (pair) {
            if (pair.indexOf(name + "=") === 0) {
                return name + "=" + value;
                found = true;
            } else {                       
              return pair;  
            }
        });

        section = pairs.join("&");
        if (!found) {
            section += "&" + name + "=" + value;
        }
    }
    return section; 

If a property exists then found will be set to true. 如果存在属性,则将found的属性设置为true。 Otherwise the property is appended to the section. 否则,该属性将附加到该部分。 Working fiddle 工作提琴

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

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