将字符串与数组匹配并替换

时间:2017-02-02 15:15:17

标签: javascript

我想知道如何将字符串与数组匹配,并替换字符串值。

我从_viewID获取了pageTitle,需要将其更改为数组中更好看的名称。

var pageTitle = [
  ["ticket_dynamic", "Dynamic ticket page"],
  ["ticket_regular", "Regular ticket page"],
  ["cart_regular", "Regular cart page"]
];
var _viewID = _viewID || [];
//_viewID = ticket_dynamic 
// _viewID needs to be Dynamic ticket page

3 个答案:

答案 0 :(得分:5)

更好的方法是使用pageTitle作为对象而不是像

这样的数组

var pageTitle = {
      "ticket_dynamic": "Dynamic ticket page",
      "ticket_regular": "Regular ticket page",
      "cart_regular": "Regular cart page"
    }
    var _viewID = "ticket_dynamic";
    var viewId = pageTitle[_viewID];
    console.log(viewId);

答案 1 :(得分:0)

如果您遇到阵列数组,那么此代码段可以执行:

var pageTitle = [
  ["ticket_dynamic", "Dynamic ticket page"],
  ["ticket_regular", "Regular ticket page"],
  ["cart_regular", "Regular cart page"]
];
var _viewID = "cart_regular";

var match = pageTitle.find((current) => current[0] == _viewID);
_viewID = match ? match[1] : "";
console.log(_viewID);

答案 2 :(得分:0)

更好的选择是更改pageTitle变量的格式。不要包含数组,只需使用对象

var pageTitle = {
    "ticket_dynamic": "Dynamic ticket page",
    "ticket_regular": "Regular ticket page",
    "cart_regular": "Regular cart page",
};

var _viewID = "ticket_dynamic";
// same as writing pageTitle.ticket_dynamic, or pageTitle["ticket_dynamic"]
// but using the variable
_viewID = pageTitle[_viewID];

// outputs "Dynamic ticket page"
console.log(_viewID);

但是如果你不能这样做,你就无法改变格式

var pageTitle = [
    ["ticket_dynamic", "Dynamic ticket page"],
    ["ticket_regular", "Regular ticket page"],
    ["cart_regular", "Regular cart page"]
];

var _viewID = "ticket_dynamic";

for (var i = 0; i < pageTitle.length; i++) {
    var keyValue = pageTitle[i]; // the array containing your key and value

    // the first element [0] will be the key
    if (keyValue[0] == _viewID) {
         _viewID = keyValue[1];
         break;
    }

    if (i + 1 == pageTitle.length) {
        // if last iteration occured, the matching key pair was not found
        // so mark _viewID as false so you know that the match was not found
        _viewID = false;
    }
}

if (_viewID) console.log(_viewID);