簡體   English   中英

如何使用'this'添加字符串

[英]How to prepend a string using 'this'

說我有一個字符串數組。 我想在每個字符串前面添加一個固定的(通用)字符串。 我知道在Javascript中,字符串可以連接,如strM = str1 + str2 + str3 + ... + strNstrM = concat(str1, str2, str3, ..., strN) 考慮一下這段代碼。

var defImgDirPath = 'res/img/';
$([
  'home-icon-dark.png',
  'home-icon-light.png'
]).each(function() {
  /*
   * Prepend each string with defImgDirPath
   */
});

現在我不能這樣做this = defImgDirPath + this; (我愚蠢到試試)

另外,我試過return (defImgDirPath + this); 但這也行不通。

我正在考慮像this.prependString(defImgDirPath);這樣的函數this.prependString(defImgDirPath); 但這樣的功能存在嗎? 如果沒有,我該怎么寫?

注意: 我知道它可以通過for循環輕松簡單地完成,但有什么好處呢? :)

var defImgDirPath = 'res/img/';
var images = [
    'home-icon-dark.png',
    'home-icon-light.png'
];
$(images).each(function(idx, val) {
  images[idx] = defImgDirPath + val;
});

console.log(images);

在最新的javascript標准(ECMA 5)中,您可以在沒有jquery的情況下執行此操作:

var defImgDirPath = 'res/img/';

['home-icon-dark.png','home-icon-light.png'].map(function(i) { 

        return defImgDirPath + i;  });

編輯:此外,jquery的map函數也類似。

問題是您正在更改數組中項目的副本,因此數組將不受影響。

循環遍歷數組中的索引並將結果放回數組中:

var arr = [ 'home-icon-dark.png', 'home-icon-light.png' ];

for (var i = 0; i < arr.length; i++) {
  arr[i] = defImgDirPath + arr[i];
}

如果你真的想從jQuery使用循環方法,那么你需要使用map ,這樣你就可以得到數組的結果。 請注意,您需要使用回調函數的參數,因為this不是數組中的項目:

arr = $.map(arr, function(str){
  return defImgDirPath + str;
});

在Javascript中, this總是指一個對象(當前上下文對象),所以它永遠不會是一個字符串,因此嘗試將它與另一個字符串連接將失敗,正如您所發現的那樣。

但是,沒有必要使用jQuery或對象來處理你正在做的事情; 你只是將一個已知值添加到每個字符串數組的開頭。

讓我們使用標准的Javascript重寫它,沒有jQuery的復雜性......

var defImgDirPath = 'res/img/';
var images = [
  'home-icon-dark.png',
  'home-icon-light.png'
];

for(var count=0; count<images.length; count++) {
    images[count] = defImgDirPath + images[count];
}

我已將images數組放入變量中,以便更容易看到實際循環代碼的作用。 如你所見,這是一個非常簡單的循環; 這里不需要jQuery魔法。

希望有所幫助。

this.prependString(defImgDirPath);

不,字符串在JavaScript中是不可變的。 連接到一個新的字符串就可以了,使用.concat會看起來像

var newString = defImgDirPath.concat(this); // no static function!

如果不存在,我該怎么寫?

你不能,因為將對象分配給“this”是不可能的。

相反,您必須分配您正在處理的數組的屬性(使用靜態$.each而不是處理集合):

var arr = [
  'home-icon-dark.png',
  'home-icon-light.png'
];
$.each(arr, function(i) {
   arr[i] = defImgDirPath + this;
});
arr[0] // res/img/home-icon-dark.png

我也試過return (defImgDirPath + this);

您需要使用map ,創建一個新數組:

var arr = $.map([
  'home-icon-dark.png',
  'home-icon-light.png'
], function(str) {
    return defImgDirPath + str;
});

當然,沒有jQuery可能會更容易:

for (var i=0; i<arr.length; i++) {
    arr[i] = defImgDirPath + arr[i];
}

並且map也可以作為本機函數使用(不在過時的瀏覽器中):

var arr = [
  'home-icon-dark.png',
  'home-icon-light.png'
].map(function(str) {
    return defImgDirPath + str;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM