我想写一个JavaScript函数,它找出最大和最小数字之间的差异。输入可以是任何数字,因此我使用<?php
class A
{
static $foo = 42;
static $baz = 4;
}
class B extends A
{
static $bar = 2;
static $baz = 44;
}
function isOwnStaticProperty($class, $prop) {
$reflect = new ReflectionClass($class);
//Filtering only the statics values with ReflectionProperty::IS_STATIC
$props = $reflect->getProperties(ReflectionProperty::IS_STATIC);
foreach ($props as $object) {
if($object->class == $class && $object->name == $prop) {
return true;
}
}
return false;
}
$class_name = 'A';
echo isOwnStaticProperty($class_name, 'foo') ? "TRUE<br>\n" : "FALSE<br>\n";
$class_name = 'B';
echo isOwnStaticProperty($class_name, 'foo') ? "TRUE<br>\n" : "FALSE<br>\n";
$class_name = 'B';
echo isOwnStaticProperty($class_name, 'bar') ? "TRUE<br>\n" : "FALSE<br>\n";
$class_name = 'A';
echo isOwnStaticProperty($class_name, 'bar') ? "TRUE<br>\n" : "FALSE<br>\n";
$class_name = 'B';
echo isOwnStaticProperty($class_name, 'baz') ? "TRUE<br>\n" : "FALSE<br>\n";
$class_name = 'A';
echo isOwnStaticProperty($class_name, 'baz') ? "TRUE<br>\n" : "FALSE<br>\n";
。
我写了一个最大和最小功能,单独他们工作正常。我把它们放在差值函数中来计算max-min并返回结果。 但是某处有一个错误,代码没有按预期运行。
arguments
答案 0 :(得分:2)
试试这个
var Doctor = bookshelf.Model.extend({
tableName: "d_doctor",
idAttribute: "d_doctorid",
patients: function() {
return this.belongsToMany(Patient).through(Appointment,"a_d_doctorid","a_p_patientid");
}
});
var Appointment = bookshelf.Model.extend({
tableName : "a_appointment",
idAttribute : "a_appointmentid",
patient: function() {
return this.belongsTo(Patient,"a_p_patientid");
},
doctor: function() {
return this.belongsTo(Doctor,"a_d_doctorid");
}
});
var Patient = bookshelf.Model.extend({
tableName : "p_patient",
idAttribute : "p_patientid",
doctors: function() {
return this.belongsToMany(Doctor).through(Appointment,"a_p_patientid", "a_d_doctorid");
}
});
无需无限
答案 1 :(得分:2)
您从不致电findMin()
或findMax()
。
您可以使用内置Math.min()
或Math.max()
,它们都可以使用无限数量的参数,因此您可以避免自己迭代参数。
像这样:
function difference() {
var min = Math.min.apply(null, arguments),
max = Math.max.apply(null, arguments);
return max - min;
}
答案 2 :(得分:0)
你可以在一个for循环中更轻松地完成它:
var numbers = [4, 8, 1, 100, 50];
function difference(arr) {
var max = arr[0]
var min = arr[0];
for(var i = 0; i < arr.length; i += 1) {
if(arr[i] > max) {
max = arr[i];
}
if(arr[i] < min) {
min = arr[i];
}
}
var d = max - min;
return d;
}
var result = difference(numbers);
console.log(result);
答案 3 :(得分:0)
如果由于某种原因您希望使用现有的findMin()
和findMax()
方法,那么您只是错过了对这些方法的调用。
在difference()
内,你应该这样做:
var numbers = Array.slice(arguments); // create an array of args
var max = findMax.apply(this, numbers);
var min = findMin.apply(this, numbers);
return max - min;
如果您希望处理负数,请按照评论的建议修复您的findMax()
方法。