使用连接字符串作为JavaScript对象属性名称

时间:2015-05-19 17:05:34

标签: javascript gulp

好吧,我需要从数组中获取所有值并将它们放在循环中,但是我无法将值传递给对象的属性名称。知道怎么做吗?

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不会将此识别为对象属性的名称...

这是我的整个Gulp代码:

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

    });
});

1 个答案:

答案 0 :(得分: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'));
});