2015-05-19 207 views
2

嗯,我需要從數組中獲取所有值並將它們放入循環中,但是我無法將該值傳遞給對象的屬性名稱。任何想法如何做到這一點?使用連接字符串作爲JavaScript對象屬性名稱

var functionCases = [ 
    "functions", 
    "document.ready", 
    "window.load", 
    "document.scroll", 
    "window.resize" 
]; 

functionCases.forEach(function(i){ 
    gulp.src(bermuda()) 
    .pipe(gfi({ 
     "/* "+ i + " */": "generator/assets/js/" + i + ".js" 
    })) 
    .pipe(gulp.dest('generator/assets/js')); 
}); 

的問題是在這裏:"/* "+ i + " */",JavaScript不認識到這一點作爲對象屬性的名稱...

這裏是我的整個咕嘟咕嘟代碼:

var gulp = require('gulp'); 
var sass = require('gulp-sass'); 
var autoprefixer = require('gulp-autoprefixer'); 
var concat = require('gulp-concat'); 
var gfi = require("gulp-file-insert"); 
var fs = require('fs'); 

gulp.task('modules', function() { 

    var bermuda = function(){ 
     var fileExist = fs.existsSync("generator/assets/js/modules.js"); 
     if (fileExist == true) { 
      var source = "generator/assets/js/modules.js"; 
      console.log("existe"); 
     } else{ 
      var source = "js/modules/modules.js"; 
      console.log("não existe"); 
     } 
     return source; 
    } 

    var functionCases = [ 
     "functions", 
     "document.ready", 
     "window.load", 
     "document.scroll", 
     "window.resize" 
    ]; 

    functionCases.forEach(function(i){ 

     console.log(i); 

     gulp.src('js/modules/**/' + i + '.js') 
      .pipe(concat('' + i + '.js')) 
      .pipe(gulp.dest('generator/assets/js')) 
      .on('end',function(){ 
       fs.exists("generator/assets/js/" + i + ".js", function(exists) { 
        if (exists) { 
         var gfiInput = {}; 
         gfiInput["/* "+ i + " */"] = "generator/assets/js/" + i + ".js"; 
         gulp.src(bermuda()) 
          .pipe(gfi(gfiInput)) 
          .pipe(gulp.dest('generator/assets/js')); 
        } 
       }); 
      }); 

    }); 
}); 
+0

http://stackoverflow.com/questions/2940424/valid-javascript-object-property-names ---但我承認,我不清楚你的問題是什麼。 –

+0

@MörreNoseshine我需要使用一個字符串作爲對象的屬性名稱... –

+2

那麼對於這種情況下,我提供了鏈接......'a = {}; a [「/ *」] = 1' - 起作用,而'a = {「/ *」}'不起作用。 –

回答

2

嘗試更換

functionCases.forEach(function(i){ 
    gulp.src(bermuda()) 
    .pipe(gfi({ 
     "/* "+ i + " */": "generator/assets/js/" + i + ".js" 
    })) 
    .pipe(gulp.dest('generator/assets/js')); 
}); 

functionCases.forEach(function(i){ 
    var gfiInput = {}; 
    gfiInput["/* "+ i + " */"] = "generator/assets/js/" + i + ".js"; 
    gulp.src(bermuda()) 
     .pipe(gfi(gfiInput)) 
     .pipe(gulp.dest('generator/assets/js')); 
}); 
+0

的作品,但現在我有另一個問題,吞嚥不尊重每個循環項目的順序,我做了循環只是想這會解決這個問題... –

+0

@CaioKawasaki你可以嘗試問另一個問題,讓有更多經驗的人可以幫助你 – howderek

相關問題