JavaScriptÖÐÈç¹ûûÓÐÏòº¯Êý²ÎÊý´«µÝÖµ£¬Ôò²ÎÊýΪundefined¡£ÎªÁËÔöÇ¿²ÎÊý¸³Öµ£¬¿ÉÒÔʹÓÃifÓï¾äÀ´Å׳öÒì³££¬»òʹÓÃÇ¿ÖƲÎÊý¼òд·½·¨¡£
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }¼òд£º
mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; } Array.find¼òдÏë´ÓÊý×éÖвéÕÒij¸öÖµ£¬ÔòÐèҪѻ·¡£ÔÚES6ÖУ¬find()º¯ÊýÄÜʵÏÖͬÑùЧ¹û¡£
<
pre>
const pets = [
{ type: 'Dog', name: 'Max'},
{ type: 'Cat', name: 'Karl'},
{ type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
for(let i = 0; i<pets.length; ++i) {
if(pets[i].type === 'Dog' && pets[i].name === name) {
return pets[i];
}
}
}
¼òд£º
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' } Object[key]¼òд¿¼ÂÇÒ»¸öÑéÖ¤º¯Êý
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true¼ÙÉèµ±ÐèÒª²»Í¬ÓòºÍ¹æÔòÀ´ÑéÖ¤£¬ÄÜ·ñ±àдһ¸öͨÓú¯ÊýÔÚÔËÐÐʱȷÈÏ£¿
// ¶ÔÏóÑéÖ¤¹æÔò const schema = { first: { required:true }, last: { required:true } } // ͨÓÃÑéÖ¤º¯Êý const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; } console.log(validate(schema, {first:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // trueÏÖÔÚ¿ÉÒÔÓÐÊÊÓÃÓÚ¸÷ÖÖÇé¿öµÄÑéÖ¤º¯Êý£¬²»ÐèҪΪÁËÿ¸ö¶ø±àд×Ô¶¨ÒåÑéÖ¤º¯ÊýÁË
Ë«ÖØ·ÇλÔËËã¼òдÓÐÒ»¸öÓÐЧÓÃÀýÓÃÓÚË«ÖØ·ÇÔËËã²Ù×÷·û¡£¿ÉÒÔÓÃÀ´´úÌæMath.floor()£¬ÆäÓÅÊÆÔÚÓÚÔËÐиü¿ì£¬¿ÉÒÔÔĶÁ´ËÎÄÕÂÁ˽â¸ü¶àλÔËËã¡£
Math.floor(4.9) === 4 //true¼òд£º
~~4.9 === 4 //true±¾ÎÄ·ÒëÓÚSitePoint£º
ÔÎĵØÖ·£ºhttps://segmentfault.com/a/1190000012673854
¡¡