如何防止在数组的最后一个值之后添加.join()的内容?

时间:2018-02-09 04:28:33

标签: javascript

var a = 0;
var b = 0;
var c = 0;
var d = 0;
var e = 0;
var f = 0;
var alphaA = $("#inOne").val();
var alphaB = $("#inTwo").val();
var betaA = parseFloat(alphaA);
var betaB = parseFloat(alphaB);
var numa = Math.abs(betaA);
var numb = Math.abs(betaB);
var factorA = [];
var factorB = [];
var commonFactor = [];

for (d = 0; d <= b; d++){
   for (e = 0; e <= c; e++){
      if (factorA[d] == factorB[e]) {
         commonFactor[f] = factorA[d];
            f++;
       }
    }
}
f--;
document.getElementById("cF").innerHTML = "Common Factors: " + commonFactor.join(", ");

如果我的数组的值是[1,2,4],则输出为 常见因素:1,2,4, 如何阻止“,”出现在4之后如何使其显示如下: 1,2,4

2 个答案:

答案 0 :(得分:0)

join()不会在最后一个字符后插入任何内容。下面是使用下划线(“_”)分隔字符串中每个字符的示例。它会在每个字符后添加下划线,但不会在最后一个字符后添加。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  WooCommerce: any;

  constructor(public navCtrl: NavController) {

    this.WooCommerce = WC({
      url: "http://localhost:8100/wordpress/wp-json/",
      consumerKey: "ck_4d99b09e85e45a11282fe2150945fc2090eea0f0",
      consumerSecret: "cs_3acf2c3eeb334ab84309e890a5070f8509de9201"
    });

    this.WooCommerce.getAsync("products").then( (data) => {
      console.log(data);
    }, (err) => {
      console.log(err);
    });

  }

}
var str = "this is to explain join";
document.getElementById("output").textContent = str.split('').join('_');

答案 1 :(得分:0)

试试这个:

[1, 2, 4, undefined, null].filter(e=>!!e).join(", ");