2017-02-02 180 views
1

我想知道如何匹配字符串與數組,並替換字符串值。匹配字符串數組並替換

我得到_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 

回答

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);

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); 
0

更好的選擇n會改變你的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); 
相關問題